var scope;
var httpService;

controllers.controller('IndexCtrl', ['$scope', '$rootScope', '$http', '$location', 'messagesSocketIO',
    function($scope, $rootScope, $http, $location, messagesSocketIO) {
        scope = $scope;
        httpService = $http;
        $rootScope.$on("$locationChangeStart", function(event, next, current) {
//        var myNext = next;
            var a = function(item, next) {
                if(item.hash && next.indexOf(item.hash) > -1){
                    $('div.sidebar li.active').removeClass('active');
                    $(item).parent('li').addClass('active');
                }else if(!item.hash){
                    $('div.sidebar li.active').removeClass('active');
                    $('div.sidebar li:first').addClass('active')
                }
            };

            $('div.sidebar a').each(function(index, item) {
                a(item, next);
            })

        });
        $scope.newMessages = 0;

        // todo: replace this to get the last 10 notifications (not stations..)
        $http(jsRoutes.controllers.MessagesController.getLastTenNotifications()).success(function(data, status, headers, config) {
            //sababa
            $scope.messages = data.map(function(d) {
                d.date = moment(d.date).format('DD/MM/YYYY HH:mm:ss');
                $scope.newMessages += d.isNew ? 1 : 0;
                return d;
            });
        }).error(function(data, status, headers, config) {
                alert("error fetching stations")
            })

        $('#stationTabs a').click(function (e) {
            e.preventDefault();
            $(this).tab('show');
        })


        $scope.receiveEvent = function(event) {
            var data = JSON.parse(event.data);

            // Handle errors
            if(data.error) {
                notificationsSocket.close();
                console.log(data.error);
                return;
            }

            $scope.$apply(function() {
                data.message.date = moment(data.message.date).format('DD/MM/YYYY HH:mm:ss');
                $scope.messages.unshift(data.message);
                console.log(data.message.text);
                $scope.newMessages += 1;
            });
        };

        messagesSocketIO.onmessage = $scope.receiveEvent;

        // Enabling Notification Popover
        $("#popoverNotifications").popover({
            html : true,
            content: function() {
                return $('#popoverNotificationsContent').html();
            },
            title: function() {
                return "Notifications";
            },
            container: 'body'
        });

        $('body').on('click', function (e) {
            $('[data-toggle=popover]').each(function () {
                // hide any open popovers when the anywhere else in the body is clicked
                if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                    $(this).popover('hide');
                }
            });
        });

        if($(window).width() < 1300){
            $('div.resolutionDependent').addClass("pull-right");
        }

        if($location.url() === '/')
            $location.path("/realTimeMap");
    }]);

function onMouseEnter(obj){
    var $elem = $(obj);
    if($elem.hasClass('newNotification')){
            httpService.post(jsRoutes.controllers.MessagesController.setOldMessage().url, scope.messages[$elem.attr('id')]).success(function() {
                $elem.removeAttr('ng-class');
                $elem.removeClass('newNotification');
                scope.newMessages -= scope.messages[$elem.attr('id')].isNew ? 1 : 0;
                scope.messages[$elem.attr('id')].isNew = false;
            });
    }

}